package com.inspector.app.ui.task

import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.inspector.app.di.util.UI
import com.inspector.app.ui.task.TaskTabAdapter.ViewHolder
import com.inspector.app.ui.vo.TaskClickType
import com.inspector.app.ui.vo.TaskItem
import com.inspector.app.ui.vo.TaskTabItem
import com.inspector.app.ui.widget.decoration.VerticalMarginItemDecoration

class TaskTabAdapter(
    private val tabItems: Array<TaskTabItem>,
    private val listener: (TaskClickType, TaskItem) -> Unit,
) : RecyclerView.Adapter<ViewHolder>() {

    private val itemSpace = UI.dpToPx(12)
    private val dip25 = UI.dpToPx(25)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val context = parent.context
        return ViewHolder(RecyclerView(context).apply {
            layoutParams = RecyclerView.LayoutParams(
                RecyclerView.LayoutParams.MATCH_PARENT,
                RecyclerView.LayoutParams.MATCH_PARENT
            ).apply {
                marginStart = itemSpace
                marginEnd = itemSpace
            }
            if (itemDecorationCount == 0) {
                addItemDecoration(
                    VerticalMarginItemDecoration(
                        verticalMargin = itemSpace, firstItemTopMargin = itemSpace, lastItemMargin = dip25
                    )
                )
            }

            layoutManager = LinearLayoutManager(context)
            itemAnimator = null
        }, listener)
    }

    override fun getItemCount(): Int = tabItems.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(tabItems[position])
    }

    class ViewHolder(
        private val rootView: RecyclerView,
        private val listener: (TaskClickType, TaskItem) -> Unit
    ) : RecyclerView.ViewHolder(rootView) {

        fun bind(item: TaskTabItem) {
            val itemAdapter = TaskAdapter(bindingAdapterPosition == 0, listener = listener)
            rootView.adapter = itemAdapter
            itemAdapter.submitList(item.tabItems)
        }
    }

}